<?php
declare (strict_types=1);

namespace app\platform\model;

use think\Collection;
use think\Exception;
use think\Model;

class Enterprise extends Model
{
    public function getAllEnterprise(array $where = []): Collection
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        return $this->where($where)->select();
    }

    public function getEnterpriseList(int $page = 1, int $limit = 10, array $where = []): Collection
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        $offset             = ($page - 1) * $limit;
        return $this->where($where)->limit($offset, $limit)->select();
    }

    public function getEnterpriseCount(array $where = []): int
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        return $this->where($where)->count();
    }

    public function findEnterpriseById(int $id)
    {
        return $this->where(['id' => $id, 'is_delete' => config('status.mysql.table_normal')])->find();
    }

    public function addEnterprise(array $data): bool
    {
        return (boolean)$this->insert($data);
    }

    public function updateEnterprise(int $id, array $data): bool
    {
        $data['updated_at'] = date('Y-m-d H:i:s');
        return (boolean)$this->where(['id' => $id])->save($data);
    }

    /**
     * @throws \Exception
     */
    public function deleteEnterprise(int $id): bool
    {
        try {
            $this->startTrans();
            $this->where(['id' => $id])->save(['is_delete' => config('status.mysql.table_delete')]);
            $this->name('website')->where(['enterprise_id' => $id])->save(['is_delete' => config('status.mysql.table_delete')]);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->rollback();
            throw  new  \Exception($e->getMessage());
        }
    }
}
